// Copyright Epic Games, Inc. All Rights Reserved.

#include "vfs_cmd.h"

#include <zencore/compactbinarybuilder.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/string.h>
#include <zencore/uid.h>
#include <zenhttp/formatters.h>
#include <zenhttp/httpclient.h>
#include <zenutil/zenserverprocess.h>

namespace zen {

using namespace std::literals;

VfsCommand::VfsCommand()
{
	m_Options.add_option("", "", "verb", "VFS management verb (mount, unmount, info)", cxxopts::value(m_Verb), "<verb>");
	m_Options.add_option("", "u", "hosturl", "Host URL", cxxopts::value(m_HostName)->default_value(""), "<url>");
	m_Options.add_option("", "", "vfs-path", "Specify VFS mount point path", cxxopts::value(m_MountPath), "<path>");

	m_Options.parse_positional({"verb", "vfs-path"});
}

VfsCommand::~VfsCommand()
{
}

int
VfsCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions, argc, argv);

	if (!ZenCmdBase::ParseOptions(argc, argv))
	{
		return 0;
	}

	// Validate arguments

	m_HostName = ResolveTargetHostSpec(m_HostName);

	if (m_HostName.empty())
		throw OptionParseException("unable to resolve server specification");

	HttpClient Http(m_HostName);

	if (m_Verb == "mount"sv)
	{
		if (m_MountPath.empty())
			throw OptionParseException("No source specified");

		CbObjectWriter Cbo;
		Cbo << "method"
			<< "mount";

		Cbo.BeginObject("params");
		Cbo << "path" << m_MountPath;
		Cbo.EndObject();

		if (HttpClient::Response Result = Http.Post("/vfs"sv, Cbo.Save()))
		{
		}
		else
		{
			Result.ThrowError("VFS mount request failed"sv);

			return 1;
		}
	}
	else if (m_Verb == "unmount"sv)
	{
		CbObjectWriter Cbo;
		Cbo << "method"
			<< "unmount";

		if (HttpClient::Response Result = Http.Post("/vfs"sv, Cbo.Save()))
		{
		}
		else
		{
			Result.ThrowError("VFS unmount request failed"sv);

			return 1;
		}
	}
	else if (m_Verb == "info"sv)
	{
		if (HttpClient::Response Result = Http.Get(fmt::format("/vfs/info")))
		{
			ExtendableStringBuilder<256> Json;
			Result.AsObject().ToJson(Json);
			ZEN_CONSOLE("{}", Json);
		}
		else
		{
			Result.ThrowError("VFS info fetch failed"sv);

			return 1;
		}
	}

	return 0;
}

}  // namespace zen
